package com.ruoyi.system.outto.game.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.model.domain.AccountInfo;
import com.ruoyi.system.model.domain.InfoImg;
import com.ruoyi.system.model.domain.SalePartner;
import com.ruoyi.system.model.mapper.AccountInfoMapper;
import com.ruoyi.system.model.mapper.InfoImgMapper;
import com.ruoyi.system.outto.core.LCConstant;
import com.ruoyi.system.outto.core.MapUntils;
import com.ruoyi.system.outto.game.CommonApi;
import com.ruoyi.system.outto.game.LDAPI;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lz
 * @version 1.0
 * @date 2022/6/5 16:19
 */
@Slf4j
@Service
public class LDAPIImpl implements LDAPI {

    @Resource
    private InfoImgMapper infoImgMapper;
    @Value("${desc.title}")
    private String descTitle;
    private SalePartner salePartner;
    @Resource
    private CommonApi commonApi;

    @Resource
    private AccountInfoMapper accountInfoMapper;


    @Override
    public AjaxResult addGame(AccountInfo accountInfo, Long userId, SalePartner salePartner) {

        String path = "/index.php/platform/add";
        this.salePartner = salePartner;
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> params = params(accountInfo, "add");
        log.info("老达添加接口请求参数={}", JSONObject.toJSONString(params));
        String response = HttpUtils.doPostForm(salePartner.getTwoOther() + path, params, null);
        log.info("老达添加接口返回参数={}", response);
        JSONObject resultJson = JSONObject.parseObject(response);
        if (!"1".equals(resultJson.getString("status"))) {
            result.put("code", 500);
        } else {
            result.put("code", 200);
            String data = resultJson.getString("data");
            JSONObject jsonObject = JSON.parseObject(data);
            String product_id = jsonObject.getString("product_id");

            AccountInfo info = accountInfoMapper.selectAccountInfoById(accountInfo.getId());
            info.setLdid(product_id);
            accountInfoMapper.updateAccountInfo(info);
        }

        result.put("req", JSONObject.toJSONString(params));
        result.put("res", response);
        result.put("msg", resultJson.getString("data"));

        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult editGame(AccountInfo accountInfo, Long userId, SalePartner salePartner) {
        String path = "/index.php/platform/edit";
        this.salePartner = salePartner;
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> params = params(accountInfo, "edit");
        log.info("老达编辑接口请求参数={}", JSONObject.toJSONString(params));
        String response = HttpUtils.doPostForm(salePartner.getTwoOther() + path, params, null);
        log.info("老达编辑接口返回参数={}", response);
        JSONObject resultJson = JSONObject.parseObject(response);

        if (!"1".equals(resultJson.getString("status"))) {
            result.put("code", 500);
        } else {
            result.put("code", 200);
        }


        result.put("req", JSONObject.toJSONString(params));
        result.put("res", response);
        result.put("msg", resultJson.getString("data"));
        return AjaxResult.success(result);
    }


    private Map<String, Object> params(AccountInfo accountInfo, String type) {

        accountInfo.setDes(descTitle+accountInfo.getId()+ " " + accountInfo.getLevel() + accountInfo.getDes());

        Map<String, Object> params = new TreeMap<>();
        params.put("app_key",this.salePartner.getSaleKey());
        if (accountInfo.getDes().length() > 100){
            params.put("title",accountInfo.getDes().substring(0,99));
        }else {
            params.put("title",accountInfo.getDes());
        }

        if (Objects.equals("edit",type)){
            params.put("id",accountInfo.getLdid());
        }else {
            params.put("id","");
        }
//        params.put("cdoe",accountInfo.getId());

        String titleImg = accountInfo.getTitleImg();
        if (StringUtils.isNotEmpty(titleImg)) {
            params.put("litpic",accountInfo.getTitleImg());
        }else {
            params.put("litpic", LCConstant.defaultImg);
        }
        params.put("code","xyr"+accountInfo.getId());
        params.put("timestamp",new Date().getTime() / 1000);

        if (Objects.equals("王者荣耀",accountInfo.getType())){
            params.put("game_id",3);

            if ("安卓Q".equals(accountInfo.getRegional())){
                params.put("qf","1");
            }
            if ("安卓WX".equals(accountInfo.getRegional())){
                params.put("qf","2");
            }
            if ("苹果Q".equals(accountInfo.getRegional())){
                params.put("qf","3");
            }
            if ("苹果WX".equals(accountInfo.getRegional())){
                params.put("qf","4");
            }
        }
        if (Objects.equals("和平精英",accountInfo.getType())){
            params.put("game_id",4);
            if ("安卓Q".equals(accountInfo.getRegional())){
                params.put("qf","1");
            }
            if ("安卓WX".equals(accountInfo.getRegional())){
                params.put("qf","2");
            }
            if ("苹果Q".equals(accountInfo.getRegional())){
                params.put("qf","3");
            }
            if ("苹果WX".equals(accountInfo.getRegional())){
                params.put("qf","4");
            }
        }
        if (Objects.equals("原神",accountInfo.getType())){
            params.put("game_id",5);
            if ("官方".equals(accountInfo.getRegional())){
                params.put("qf","1");
            }
            if ("B服".equals(accountInfo.getRegional())){
                params.put("qf","2");
            }

        }
        if (Objects.equals("火影忍者",accountInfo.getType())){
            params.put("game_id",6);
        }
        if (Objects.equals("英雄联盟",accountInfo.getType())){
            params.put("game_id",7);

            String s = HttpUtils.sendGet("https://www.laodas.com/index.php/platform/dq?id=7", null);
            JSONObject jsonObject = JSON.parseObject(s);
            JSONObject data = jsonObject.getJSONObject("data");
            for (String s1 : data.keySet()) {
                String string = data.getString(s1);
                if (string.equals(accountInfo.getRegional())){
                    params.put("qf",s1);
                }
            }

        }
        if (Objects.equals("CF端游",accountInfo.getType())){
            params.put("game_id",10);

            if ("东部大区".equals(accountInfo.getRegional())){
                params.put("qf","1");
            }
            if ("北部大区".equals(accountInfo.getRegional())){
                params.put("qf","2");
            }
            if ("西部大区".equals(accountInfo.getRegional())){
                params.put("qf","3");
            }
            if ("南部大区".equals(accountInfo.getRegional())){
                params.put("qf","4");
            }
        }
        if (Objects.equals("永劫无间",accountInfo.getType())){
            params.put("game_id",2);
            if ("Steam".equals(accountInfo.getRegional())){
                params.put("qf","1");
            }
            if ("网易".equals(accountInfo.getRegional())){
                params.put("qf","2");
            }
        }
        BigDecimal bigDecimal = commonApi.addPrice(accountInfo.getPrice(),  this.salePartner.getSeleep());
        commonApi.setPrice(bigDecimal,accountInfo.getId(), this.salePartner);
        params.put("price",bigDecimal);

        params.put("body",accountInfo.getDes());

        InfoImg infoImg = new InfoImg();
        infoImg.setInfoId(accountInfo.getId());
        infoImg.setType(Constants.STR_1);
        List<InfoImg> infoImgs = infoImgMapper.selectInfoImgList(infoImg);
        String imgs = "";
        if (!CollectionUtils.isEmpty(infoImgs)) {
            imgs = infoImgs.stream().map(i -> i.getImgUrl()).collect(Collectors.joining("||"));
        } else {
            imgs =  LCConstant.defaultImg;
        }
        params.put("pictures",imgs);
        params.put("body",accountInfo.getDes());
        params.put("description",accountInfo.getDes());

        String cover = MapUntils.getCover(params);
        cover = cover.substring(0,cover.length()-1);
        cover = cover +  this.salePartner.getOther();
        log.info("cover={}", cover);
        String sign = DigestUtils.md5Hex(cover);
        log.info("sign={}", sign);
        params.put("sign", sign);
        return params;
    }


    @Override
    public AjaxResult delGame(AccountInfo accountInfo, Long userId, SalePartner sa) {
        Map<String, Object> params = new TreeMap<>();
        params.put("app_key", sa.getSaleKey());
        params.put("product_id", accountInfo.getLdid());
        params.put("timestamp", new Date().getTime() / 1000);
        params.put("status", "2");

        String path = "/index.php/platform/show";

        //sign
        String cover = MapUntils.getCover(params);
        cover = cover.substring(0,cover.length()-1);
        cover = cover +  sa.getOther();
        log.info("cover={}", cover);
        String sign = DigestUtils.md5Hex(cover);
        log.info("sign={}", sign);
        params.put("sign", sign);
        log.info("老达删除接口请求参数={}", JSONObject.toJSONString(params));
        String response = HttpUtils.doPostForm(sa.getTwoOther() + path, params, null);
        if (StringUtils.isEmpty(response)) {
            throw new GlobalException("请求接口失败");
        }
        log.info("老达删除接口返回参数={}", JSONObject.toJSONString(response));
        JSONObject resultJson = JSONObject.parseObject(response);
        Map<String, Object> result = new HashMap<>();

        if (!"1".equals(resultJson.getString("status"))) {
            result.put("code", 500);
        } else {
            result.put("code", 200);
            AccountInfo info = accountInfoMapper.selectAccountInfoById(accountInfo.getId());
            info.setLdid(null);
            accountInfoMapper.updateAccountInfo(info);
        }

        result.put("req", JSONObject.toJSONString(params));
        result.put("res", response);
        result.put("msg", resultJson.getString("data"));
        return AjaxResult.success(result);
    }


    public static void main(String[] args) {
        JSONObject data = new JSONObject();

        data.put("1","弗雷尔卓德");
        for (String s1 : data.keySet()) {
            System.out.println(s1);
            System.out.println(data.getString(s1));
        }

    }

}
